package com.util;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.List;
import java.util.Map;

/**
 * 前面相关的工具类
 * @author  yuejing
 * @email   yuejing0129@163.com 
 * @date    2016年3月2日 下午4:20:28 
 * @version 1.0.0
 */
public class AuthUtil {

    //url的权限类型
    //0 无权限
    //1 用户权限
    //2 api权限
    //404 无URL信息
    public static Integer authVerifyReqUrl( List<Map> urlList , String reqUrl){
        for(Map o : urlList){

            if(isMatch(reqUrl,o.get("url").toString())){
                return (Integer) o.get("authorization");
            }
        }

        return 404;
    }


	/**
	 * 匹配字符串规则是否一致
	 * @param curStr
	 * @param matchStr
	 * @return
	 */
	private static boolean isMatch(String curStr, String matchStr) {
		List<String> curList = FrameStringUtil.toArray(curStr, "/");
		List<String> matchList = FrameStringUtil.toArray(matchStr, "/");
		if(curList.size() < matchList.size()) {
			//长度不一致
			return false;
		}
		String match = null;
		for (int i = 0; i < curList.size(); i ++) {
			String cur = curList.get(i);
			if(i < matchList.size()) {
				match = matchList.get(i);
				if(cur.equals(match) || match.equals("*") || match.equals("**")) {
					//处理 /test/index => /test/**
					//处理 /test/index => /test/*
					continue;
				} else {
					return false;
				}
			} else if(i >= matchList.size() && "**".equals(match)) {
				//处理 /test/index/1 => /test/**
				continue;
			} else {
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) {
        ShardedJedis jedis = null;
        try {
            jedis = RedisClient.getRedisClient();
            //jedis.set(serviceName,json.toString());
           /* for(Map<String, Object>objectMap : list){
                jedis.hset(objectMap.get("micro").toString() ,objectMap.get("type")+getStringForKey("/"+objectMap.get("micro").toString()+objectMap.get("url").toString()),objectMap.get("authorization").toString());
            }*/
           String url = "GET/microClient/say";
           String str = jedis.get("microClient");
            List<Map>  jsonObject = JSONObject.parseArray(str, Map.class);
           for(Map o : jsonObject){



               System.out.println(isMatch(url,o.get("url").toString()));
           }



        } catch (JedisConnectionException e) {
            // LOGGER.error("redis 链接异常: " + e.getMessage());
            //  counter();
        } catch (Exception e) {
            //  LOGGER.error("redis 异常: " + e.getMessage(), e);
        } finally {
            //jedis.returnRes(jedis);
        }

	}
}